package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.map.City;
import com.cljz.makepassenger.model.net.bean.GetCityBean;
import com.cljz.makepassenger.present.activity.MapP;
import com.cljz.makepassenger.service.LocationService;
import com.cljz.makepassenger.ui.adapter.MapAddressListAdapter;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.widget.ClearEditText;
import com.jakewharton.rxbinding.view.RxView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/7.
 */

public class MapActivity extends BaseActivity<MapP> implements BDLocationListener, OnGetGeoCoderResultListener {
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.cet_search)
    ClearEditText cetSearch;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.activity_map_toolbar)
    RelativeLayout activityMapToolbar;
    @BindView(R.id.cv_title)
    CardView cvTitle;
    @BindView(R.id.mv_baidu)
    TextureMapView mvBaidu;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.tv_current_position)
    TextView tvCurrentPosition;
    @BindView(R.id.rv_address)
    RecyclerView rvAddress;
    @BindView(R.id.ll_map)
    LinearLayout llMap;
    @BindView(R.id.rl_map)
    RelativeLayout rlMap;
    @BindView(R.id.activity_map)
    LinearLayout activityMap;
    private LocationService locationService;
    private City city = new City();
    private LocationClient client = null;
    private BaiduMap baiduMap;
    private GeoCoder mSearch;
    private MapAddressListAdapter mapAddressListAdapter;
    private List<City> suggestionInfoList = new ArrayList<>();
    private boolean hasResult = false;
    private String locationCity;
    private boolean needLocation = true;
    private PoiSearch mPoiSearch;
    private BitmapDescriptor mark;
    private BitmapDescriptor mCurrentMarker;


    @Override
    public void initData(Bundle savedInstanceState) {
        initMap();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAddress.setLayoutManager(layoutManager);
        mapAddressListAdapter = new MapAddressListAdapter(App.getInstance(), suggestionInfoList);
        rvAddress.setAdapter(mapAddressListAdapter);

    }

    private void initMap() {
        mark = BitmapDescriptorFactory.fromResource(R.mipmap.map_address);
        locationService = App.getLocationService();
        mvBaidu.removeViewAt(1);


        client = new LocationClient(getApplicationContext());


        //设置定位SDK的定位方式
        LocationClientOption clientOption = new LocationClientOption();
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认gcj02，设置返回的定位结果坐标系
        clientOption.setCoorType("bd09ll");
        //可选，设置是否需要地址信息，默认不需要
        clientOption.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        clientOption.setOpenGps(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        clientOption.setLocationNotify(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        clientOption.setIsNeedLocationDescribe(true);
        clientOption.setScanSpan(0);
        client.setLocOption(clientOption);
        client.setLocOption(locationService.getDefaultLocationClientOption());
        client.registerLocationListener(this);
        client.start();

        baiduMap = mvBaidu.getMap();
        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mapLocation(latLng);

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.getUiSettings().setAllGesturesEnabled(true);


        //实例化一个地理编码查询对象
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);


    }

    private void mapLocation(LatLng latLng) {
        //获取经纬度
        double latitude = latLng.latitude;
        double longitude = latLng.longitude;

        //清除图层
        baiduMap.clear();
        // 定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);
        // 构建MarkerOption，用于在地图上添加Marker
        MarkerOptions options = new MarkerOptions().position(point).icon(mark);
        // 在地图上添加Marker，并显示
        baiduMap.addOverlay(options);
        suggestionInfoList.clear();
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(cetSearch)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).putString("city", tvCity.getText().toString().trim()).requestCode(11).to(SearchSiteActivity.class).launch();

                    }
                });
        RxView.clicks(tvCity)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance()).putString("city", tvCity.getText().toString().trim()).requestCode(123).to(CityListActivity.class).launch();
                    }
                });
        RxView.clicks(tvCancel)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.pop(MapActivity.this);
                    }
                });
        RxView.clicks(ivLocation)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        needLocation = true;
                    }
                });

        mapAddressListAdapter.setOnItemClickListener(new MapAddressListAdapter.OnItemClickListener() {
            @Override
            public void onClick(City city) {
                Intent intent = new Intent();
                MapActivity.this.city.setAreaName(city.getAreaName());
                MapActivity.this.city.setAddress(city.getAddress());
                MapActivity.this.city.setLatitude(city.getLatitude());
                MapActivity.this.city.setLongitude(city.getLongitude());
//                intent.putExtra("data", MapActivity.this.city);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", MapActivity.this.city);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onLongClick(City city) {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        hasResult = true;
        final City city = (City) data.getSerializableExtra("data");
        if (requestCode == 123 && resultCode == RESULT_OK) {
            this.city.setAreaName(city.getAreaName());
            this.city.setProvice(city.getProvice());
            this.city.setAddress(city.getAreaName());
            tvCity.setText(city.getCityName());
            suggestionInfoList.clear();
            LatLng latLng = new LatLng(city.getLatitude(), city.getLongitude());
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom((latLng), 17.0f);
            baiduMap.animateMapStatus(u);
            mapLocation(latLng);
            tvCurrentPosition.setText("[搜索结果]");
        } else if (requestCode == 11 && resultCode == RESULT_OK) {
            LatLng latLng = new LatLng(city.getLatitude(), city.getLongitude());
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom((latLng), 17.0f);
            baiduMap.animateMapStatus(u);
            mapLocation(latLng);
            tvCurrentPosition.setText("[搜索结果]");
//            suggestionInfoList.clear();
            suggestionInfoList.add(0, city);
            tvCity.setText(city.getCityName());
            mapAddressListAdapter.setSuggestionInfoList(suggestionInfoList);
        }
//        LatLng latLng = new LatLng(city.getLatitude(), city.getLongitude());
//        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom((latLng), 17.0f);
//        baiduMap.animateMapStatus(u);
//        mapLocation(latLng);
//        tvCurrentPosition.setText("[搜索结果]");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    public MapP newP() {
        return new MapP();
    }

    @Override
    protected void setScreen() {
        super.setScreen();
        hideSoftKeyboard();
        SDKInitializer.initialize(getApplicationContext());

    }

    @Override
    public void onReceiveLocation(final BDLocation bdLocation) {
        locationCity = bdLocation.getCity();
        //将获取的location信息给百度map
        MyLocationData data = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(bdLocation.getDirection())
                .latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude())
                .build();
        // 设置定位数据
        baiduMap.setMyLocationData(data);
        if (needLocation) {
            //获取经纬度
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                    .zoom(18)
                    .build();

            mapLocation(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));


            MapStatusUpdate status = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            baiduMap.animateMapStatus(status);//动画的方式到中间
            baiduMap.setMapStatus(status);
            needLocation = false;
            // 设置定位数据
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    tvCity.setText(bdLocation.getCity());
                }
            };
            runOnUiThread(runnable);
            suggestionInfoList.clear();
            getP().getCity(bdLocation.getProvince(), bdLocation.getCity());
        }
        if (hasResult) {
            L.e(bdLocation.getProvince(), bdLocation.getCity());
            getP().getCity(bdLocation.getProvince(), bdLocation.getCity());
            hasResult = false;
        }

        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude())));

    }


    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult != null && reverseGeoCodeResult.getPoiList() != null)
            for (int i = 0; i < reverseGeoCodeResult.getPoiList().size(); i++) {
                PoiInfo poiInfo = reverseGeoCodeResult.getPoiList().get(i);
                City city = new City();
                city.setAreaName(poiInfo.name);
                city.setAddress(poiInfo.address);
                city.setLongitude(poiInfo.location.longitude);
                city.setLatitude(poiInfo.location.latitude);
                if (suggestionInfoList.size() < 3) {
                    suggestionInfoList.add(city);
                }
            }
        mapAddressListAdapter.setSuggestionInfoList(suggestionInfoList);
    }

    @Override
    protected void onStop() {
        super.onStop();
        baiduMap.setMyLocationEnabled(false);
        client.stop();
        client.unRegisterLocationListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        baiduMap.setMyLocationEnabled(false);
        if (!client.isStarted()) {
            client.start();
            client.registerLocationListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mvBaidu.onDestroy();
    }

    @Override
    protected void onResume() {
        mvBaidu.setVisibility(View.VISIBLE);
        mvBaidu.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mvBaidu.setVisibility(View.INVISIBLE);
        mvBaidu.onPause();
        super.onPause();
    }

    public void getCityFail(String error) {
    }

    public void getCitySucceed(GetCityBean getCityBean) {
        city.setCity_id(getCityBean.getData().getCity_id());
    }
}
